package com.sca.point.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author liuxianfei
 * @since 2020/12/7 12:04
 */
@Slf4j
@Component
public class RedisLockUtil {

    private final RedisTemplate<String, Object> redisTemplate;
    private volatile Object mutexDoNotUseDirectly;

    public RedisLockUtil(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private Object mutex() {
        Object mutex = mutexDoNotUseDirectly;
        if (mutex == null) {
            synchronized (this) {
                mutex = mutexDoNotUseDirectly;
                if (mutex == null) {
                    mutexDoNotUseDirectly = mutex = new Object();
                }
            }
        }
        return mutex;
    }

    public void lock(String key) {
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, 1, 3600, TimeUnit.SECONDS);
        if (flag != null && flag) {
            return;
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        lock(key);
    }

    public void unLock(String key) {
        redisTemplate.delete(key);
    }


}
